#!/usr/bin/env python3.11
# -*- encoding: utf-8 -*-
"""
@File    :   schemas.py
@Time    :   2024/06/17 15:06:03
@Author  :   windstarry 
@Version :   1.0
"""
# here put the import lib
from ninja_schema import ModelSchema, model_validator
from django.db import transaction
from typing import List, Optional, Type, Any
from ninja_extra import service_resolver
from ninja_extra.controllers import RouteContext


from core.schemas import CoreModelSchema
from .models import MenuModel


class MenuInfoSchema(ModelSchema):
    type: int
    status: int
    class Config:
        model = MenuModel
        include = (
            "id",
            "name",
            "icon",
            "path",
            "pid",
            "component",
            "identifier",
            "api",
            "method",
        )


class MenuInSchema(CoreModelSchema):
    type: int = 0
    status: int = 1
    class Config:
        model = MenuModel
        include = (
            "name",
            "icon",
            "path",
            "pid",
            "component",
            "identifier",
            "api",
            "method",
        )
        
    @transaction.atomic
    def create(self, **kwargs: Any):
        """
        创建菜单实例。

        参数:
        self -- 实例本身。
        **kwargs -- 创建用户时额外传递的关键字参数。

        返回值:
        返回创建的菜单模型的实例。

        """
        # 获取当前的路由上下文，并从中解析出请求用户
        context: RouteContext = service_resolver(RouteContext)
        # 创建一个字典，排除None值
        _data = self.dict(exclude_none=True)
        # 设置创建者和修改者为当前请求的用户
        _data["creator"] = context.request.user
        _data["modifier"] = context.request.user
        # 更新字典数据，加入额外的kwargs参数
        _data.update(kwargs)
        # 使用提供的数据创建用户实例并返回
        return MenuModel.objects.create(**_data)
    
    
    @transaction.atomic
    def update(self, instance: Any, **kwargs: Any) -> Any:
        context: RouteContext = service_resolver(RouteContext)
        _data = self.dict(exclude_none=True)
        # 设置修改者为当前请求的用户
        _data["modifier"] = context.request.user
        # 更新字典数据,加入额外的kwargs参数
        _data.update(kwargs)
        return super().update(instance, **_data)

    
    

    

        
